package com.channel.temperature.collect.app.ble;

import android.util.Log;

import java.security.SecureRandom;


public class SHLockCmd {

    private static int key = 0;

    public SHLockCmd() {
        key = Math.abs(new SecureRandom().nextInt()) % 0x64;
//            key =2 ;
        Log.e("openLock", "openLock key:" + key);
    }


    public static byte[] Decryption(byte[] cipher, byte key, int start, int len) {
        for (int i = start; i < start + len; ++i) {
            cipher[i] = ((byte) (cipher[i] ^ key));
            cipher[i] = ((byte) SYMM_SWAP(cipher[i]));
        }
        return cipher;
    }

    //加密
    private byte[] Encryption(byte[] original, int start, int len) {
        for (int i = start; i < start + len; ++i) {
            original[i] = (byte) (((byte) SYMM_SWAP(original[i])) ^ ((byte) key));
        }
        original[start + len] = ((byte) key);
        return original;
    }

    public static int SYMM_SWAP(byte key) {
        return ((key & 1) << 7) | ((key & 2) << 5) | ((key & 4) << 3) | ((key & 8) << 1) | ((key & 0x10) >> 1)
                | ((key & 0x20) >> 3) | ((key & 0x40) >> 5) | ((key & 0x80) >> 7);
    }


    public static byte colCheckByte(byte[] datamsg, int start, int len) {
        byte check = 0;
        for (int i = start; i < start + len; ++i) {
            check = ((byte) (datamsg[i] ^ check));
        }

        return check;
    }

    //构建发送的数据包  datamsg  - (len 加密数据 key)
    private byte[] packageData(byte[] datamsg) {
        byte[] data = new byte[datamsg.length + 1];
        System.arraycopy(datamsg, 0, data, 0, datamsg.length);
        data[datamsg.length] = colCheckByte(datamsg, 0, datamsg.length);
        byte[] dataSend = new byte[data.length + 2];
        System.arraycopy(data, 0, dataSend, 2, data.length);
        dataSend[0] = (byte) 0xaa;
        dataSend[1] = (byte) 0xbb;
        // EkitLog.debug(v1);
        return dataSend;
    }

    //蓝牙锁调这个命令-----

    public byte[] sendLockCmd(byte[] cmd) {
        byte[] send = new byte[cmd.length];
        System.arraycopy(cmd, 0, send, 0, cmd.length);
        return packageData(Encryption(send, 1, (send[0] & 0xFF) - 2));    //对原来的明文指令中的“命令字、数据域”进行加密
    }


}
